import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:my_shop/widget/common_dialog.dart';


class GZXQuantityDialogWidget extends StatefulWidget {
  const GZXQuantityDialogWidget(
      {Key? key,
        this.quantity = 1,
        this.addTap,
        this.delayAddTap,
        this.removeTap,
        this.delayRemoveTap,
        this.borderColor = const Color(0xFFE6E6E6),
        this.updateValueChanged,
        this.height = 28,
        this.maxNumber = 9999,
        this.inputFormatters})
      : super(key: key);
  final int quantity;
  final ValueChanged<int>? addTap;
  final ValueChanged<int>? delayAddTap;
  final ValueChanged<int>? removeTap;
  final ValueChanged<int>? delayRemoveTap;
  final Color borderColor;
  final double height;
  final ValueChanged<String>? updateValueChanged;
  final int? maxNumber;
  final List<TextInputFormatter>? inputFormatters;

  @override
  // ignore: library_private_types_in_public_api
  _GZXQuantityDialogWidgetState createState() =>
      _GZXQuantityDialogWidgetState();
}

class _GZXQuantityDialogWidgetState extends State<GZXQuantityDialogWidget> {
  var textController = TextEditingController();

  var tempTextController = TextEditingController();

  FocusNode focusNode = FocusNode();

  DateTime? _addLastTime;
  DateTime? _removeLastTime;

  @override
  void initState() {
    super.initState();
    final String count = widget.quantity.toString();
    textController.text = count;

    focusNode.addListener(() {
      if (focusNode.hasFocus) {
      } else {
        if (textController.text == '') {
          widget.updateValueChanged!('1');
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    textController.text = widget.quantity.toString();
    return Container(
      height: widget.height,
      decoration: BoxDecoration(
          borderRadius: const BorderRadius.all(Radius.circular(2)),
          border: Border.all(color: widget.borderColor)),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          GestureDetector(
            // onTap: widget.removeTap,
            onTap: () {
              if (textController.text == '') {
                textController.text = '1';
              }
              int num = int.parse(textController.text);
              if (num > 1) {
                num--;
                final String str = '$num';
                textController.text = str;
                if (widget.removeTap != null) {
                  widget.removeTap!(num);
                }
              }
              textController.selection = TextSelection.fromPosition(
                  TextPosition(offset: textController.text.length));

              if (widget.delayRemoveTap != null) {
                final DateTime tempAddTime = DateTime.now();
                _addLastTime = tempAddTime;
                Future.delayed(const Duration(milliseconds: 2000), () {
                  if (tempAddTime == _addLastTime) {
                    widget.delayRemoveTap!(num);
                  }
                });
              }
            },
            child: Container(
              alignment: Alignment.center,
              width: 25,
              height: 25,
              decoration: BoxDecoration(
                  border: _getRemoveButtonBorder(),
                  color: const Color(0xFFF2F2F2),),
              child: const Icon(
                Icons.remove,
                color: Color(0xFF333333),
                size: 20,
              ),
            ),
          ),
          Container(
            alignment: Alignment.center,
            width: 55,
            child: TextField(
              // inputFormatters: widget.inputFormatters ??
              //     <TextInputFormatter>[
              //       UsIntTextInputFormatter(),
              //     ],
              readOnly: true,
              controller: textController,
              focusNode: focusNode,
              onTap: () {
                tempTextController.text = textController.text;
                showCountDialog();
              },
              keyboardType: TextInputType.number,
              textAlign: TextAlign.center,
              style: const TextStyle(fontSize: 12),
              enableInteractiveSelection: false,
              onChanged: (value) {
                widget.updateValueChanged!(value);
              },
              onEditingComplete: () {},
              onSubmitted: (value) {},
              decoration: const InputDecoration(
                contentPadding: EdgeInsets.only(top: 2, bottom: 2),
                border: OutlineInputBorder(
                  gapPadding: 0,
                  // ignore: use_named_constants
                  borderSide: BorderSide(
                    width: 0,
                    style: BorderStyle.none,
                  ),
                ),
              ),
            ),
          ),
          GestureDetector(
            // onTap: widget.addTap,
            onTap: () {
              if (textController.text == '') {
                textController.text = '1';
              }
              int num = int.parse(textController.text);

              if (widget.maxNumber! > num) {
                num++;
                textController.text = '$num';
              } else {
                Fluttertoast.showToast( msg: 'Quantity exceeds available stock. Please adjust.');
              }
              textController.selection = TextSelection.fromPosition(
                  TextPosition(offset: textController.text.length));
              if (widget.addTap != null) {
                widget.addTap!(num);
              }
              if (widget.delayAddTap != null) {
                final DateTime tempAddTime = DateTime.now();
                _removeLastTime = tempAddTime;
                Future.delayed(const Duration(milliseconds: 2000), () {
                  if (tempAddTime == _removeLastTime) {
                    widget.delayAddTap!(num);
                  }
                });
              }
            },
            child: Container(
              alignment: Alignment.center,
              width: 25,
              height: 25,
              decoration: BoxDecoration(
                  border: _getAddButtonBorder(), color: const Color(0xFFF2F2F2)),
              child: const Icon(
                Icons.add,
                color: Color(0xFF333333),
                size: 20,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Border _getRemoveButtonBorder() {
    return Border(
      right: BorderSide(color: widget.borderColor),
    );
  }

  Border _getAddButtonBorder() {
    return Border(
      left: BorderSide(color: widget.borderColor),
    );
  }

  void showCountDialog() {
    showDialog<void>(
        context: context,
        builder: (_) => CommonDialog(
          title: 'Modify Purchase Quantity',
          titleColor: Colors.black,
          contentWidget: Container(
            alignment: Alignment.center,
            // width: 55,
            child: TextField(
              // inputFormatters: widget.inputFormatters ??
              //     <TextInputFormatter>[
              //       UsIntTextInputFormatter(),
              //     ],
              controller: tempTextController,
              focusNode: focusNode,
              keyboardType: TextInputType.number,
              style: const TextStyle(fontSize: 16),
              enableInteractiveSelection: false,
              decoration: const InputDecoration(
                border: OutlineInputBorder(
                  gapPadding: 0,
                  borderSide: BorderSide(
                    color: Color(0xFFFF8400),
                    style: BorderStyle.none,
                  ),
                ),
              ),
            ),
          ),
          confirmTitle: 'Confirm',
          onConfirmPressed: () {
            textController.text = tempTextController.text.isEmpty
                ? '1'
                : tempTextController.text;
            widget.updateValueChanged!(
                textController.text.isEmpty ? '1' : textController.text);
            Navigator.pop(context);
          },
        ));
  }
}
